<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {
	function __construct() {
		parent::__construct();
		session_start();
		unset($_SESSION['public_folder']);
		unset($_SESSION['index_banner']);
		unset($_SESSION['static_page']);

		if (SITE_CLOSE == 1 && url_contains("frontend")) {
			redirect(BASE_URL);
		}

		// --------- 非法登录验证 ---------
		if (url_contains("backend")) {
			if (empty($_SESSION)) { show_404(); }
			
			//URL包含society的就是society的验证
			if (url_contains('society')) {
				if ($_SESSION['ucid'] != SOCIETY_UCID) { show_404(); }
				
				//社团非法使用功能验证
				if (url_contains(array("upload", "news", "announcement", "file"))) {
					if ($_SESSION['confirm_FLAG'] != SOCIETY_FINAL_PASS) { show_404(); }
				}
			}

			//URL包含association的就是association的验证
			if (url_contains('association')) {
				if ($_SESSION['ucid'] != ASSOCIATION_UCID) { show_404(); }
				
				//社联成员非法使用功能验证
				// --------- 部门功能账号的验证 ---------
				if (url_contains(array("update_info", "show_change_password", "show_change_email"))) {
					if ($_SESSION['function_FLAG'] == IS_FUNCTION) { show_404(); }
				}

				// --------- 宣传部功能账号的验证 ---------
				if (url_contains(array("news", "announcement"))) {
					if ($_SESSION['cid'] != ASSOCIATION_XCB_CID OR $_SESSION['function_FLAG'] != IS_FUNCTION) { show_404(); }
				}

				// --------- 社团管理部功能账号的验证 ---------
				if (url_contains(array("verify", "file"))) {
					if ($_SESSION['cid'] != ASSOCIATION_STGLB_CID OR $_SESSION['function_FLAG'] != IS_FUNCTION) { show_404(); }
				}
			}
				
			//URL包含teacher的就是teacher的验证
			if (url_contains('teacher')) {
				if ($_SESSION['ucid'] != TEACHER_UCID) { show_404(); }
			}
		}

		//URL包含ADMIN_FOLDER的就是admin的验证
		if (url_contains(ADMIN_FOLDER . '/admin')) {
			if (empty($_SESSION)) { show_404(); }
			
			if ($_SESSION['ucid'] != ADMIN_UCID) { show_404(); }
		}

	}

	/**
	 * 登录用户信息绑定
	 */
	function login_user_info() {
		if (empty($_SESSION)) { return FALSE; }
		switch ($_SESSION['ucid']) {
			case SOCIETY_UCID:
				$data['user_name'] = $this->session->userdata(SESSION_SOCIETY_NAME);
				break;
			case ASSOCIATION_UCID:
				$data['user_name'] = $this->session->userdata(SESSION_ASSOCIATION_NAME);
				if ($_SESSION['function_FLAG'] == IS_FUNCTION) {
					$data['department_name'] = $this->common_data->_get_association_category_name_by_cid($_SESSION['cid']);
				}
				break;
			case TEACHER_UCID:
				$data['user_name'] = $this->session->userdata(SESSION_TEACHER_NAME);
				break;
			case ADMIN_UCID:
				$data['user_name'] = $this->session->userdata(SESSION_ADMIN_NAME);
				break;
		}
		return $data;
	}

	/**
	 * 登录用户后台侧栏信息绑定
	 */
	function sidebar_info() {
		switch ($_SESSION['ucid']) {
			case SOCIETY_UCID:
				$data['re_society_name'] = $this->session->userdata(SESSION_SOCIETY_RE_NAME);
				$data['logo_thumb'] = $this->session->userdata(SESSION_SOCIETY_LOGO_THUMB);
				$data['re_person'] = $this->session->userdata(SESSION_SOCIETY_RE_PERSON);
				$data['status'] = $this->common_data->_get_society_status_by_confirm_flag($_SESSION['confirm_FLAG']);
				break;
			case ASSOCIATION_UCID:
				$data['department_name'] = $this->common_data->_get_association_category_name_by_cid($_SESSION['cid']);
				if ($_SESSION['function_FLAG'] == IS_FUNCTION) {
					$data['re_name'] = $data['department_name'] . ' - ' . IS_FUNCTION_CHS;
				} else {
					$data['re_name'] = $this->session->userdata(SESSION_ASSOCIATION_RE_PERSON);
					$data['status'] = $this->common_data->_get_association_status_by_confirm_flag($_SESSION['confirm_FLAG']);
				}
				break;
			case TEACHER_UCID:
				$data['re_name'] = $this->session->userdata(SESSION_TEACHER_RE_PERSON);
				$data['direct_society'] = $this->session->userdata(SESSION_TEACHER_DIRECT_SOCIETY);
				break;
		}
		return $data;
	}

	/**
	 * 得到表单数据
	 * @param $unset 过滤数据 可以是字符串 也可以是数组
	 */
	function _get_form_array($unset = "") {
		$form_data = array();

		foreach ($_POST as $k => $v) {
			if (is_array($unset)) {
				if (!in_array($k, $unset)) {
					$form_data[$k] =  $v;
				}
			} else {
				if ($k != $unset) {
					$form_data[$k] =  $v;
				}
			}
		}
		return $form_data;
	}

	/**
	 * 得到session中社团的用户名
	 */
	function _get_society_name() {
		$society_name = $this->session->userdata(SESSION_SOCIETY_NAME);
		return $society_name;
	}

	/**
	 * 得到session中社联员工的用户名
	 */
	function _get_association_name() {
		$association_name = $this->session->userdata(SESSION_ASSOCIATION_NAME);
		return $association_name;
	}

	/**
	 * 得到session中社团指导老师的用户名
	 */
	function _get_teacher_name() {
		$association_name = $this->session->userdata(SESSION_TEACHER_NAME);
		return $association_name;
	}

	/**
	 * 得到session中管理员的用户名
	 */
	function _get_admin_name() {
		$admin_name = $this->session->userdata(SESSION_ADMIN_NAME);
		return $admin_name;
	}

	function _ajax_validate($validate_data) {
		if (isset($validate_data['name'])) {
			$name = $validate_data['name'];
			if ($name == '') {
				$this->output->set_output(json_encode('null_username_error'));
				return FALSE;
			} elseif (mb_strlen($name) > 16 OR mb_strlen($name) < 5) {
				$this->output->set_output(json_encode('name_length_error'));
				return FALSE;
				//"regexp"=>"/^[0-9a-zA-Z\xa1-\xff\x80-\xff]+$/"
			} elseif (!filter_var($name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z][a-zA-Z0-9_]+$/")))) {
				$this->output->set_output(json_encode('name_pattern_error'));
				return FALSE;
			}
		}

		if (isset($validate_data['email'])) {
			$email = $validate_data['email'];
			if ($email == '') {
				$this->output->set_output(json_encode('null_email_error'));
				return FALSE;
				//"regexp"=>"/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/"
			} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				$this->output->set_output(json_encode('email_pattern_error'));
				return FALSE;
			}
		}

		if (isset($validate_data['password'])) {
			$password = $validate_data['password'];
			if ($password == '') {
				$this->output->set_output(json_encode('null_password_error'));
				return FALSE;
			} elseif (mb_strlen($password) > 10 OR mb_strlen($password) < 4) {
				$this->output->set_output(json_encode('password_length_error'));
				return FALSE;
			}
		}

		if (isset($validate_data['keywords'])) {
			$keywords = $validate_data['keywords'];
			if ($keywords == '') {
				$this->output->set_output(json_encode('null_keywords_error'));
				return FALSE;
			} elseif (mb_strlen($keywords) > 20) {
				$this->output->set_output(json_encode('max_keywords_error'));
				return FALSE;
			} elseif (!filter_var($keywords, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9a-zA-Z\xa1-\xff\x80-\xff]+$/")))) {
				$this->output->set_output(json_encode('special_keywords_error'));
				return FALSE;
			}
		}

		return TRUE;
	}

	/**
	 * get info of society
	 * @param $sciety_id
	 */
	function _get_society_info($sciety_id) {
		$data['society'] = $this->society_model->_get_by_foreign_id($sciety_id);
		$data['teacher'] = $this->teacher_model->_get_by_foreign_id($data['society']['s_teacher']);
		return $data;
	}

	/**
	 * get society signin log by society ID/serialized signin log automatically
	 * @param $by_data: $society_id/$serialized_signin_log
	 */
	function _get_society_sigin_log($by_data) {
		switch (filter_var($by_data, FILTER_VALIDATE_INT)) {
			case TRUE:
				$society_id = $by_data;
				$serialized_signin_log = $this->society_model->_get_by_foreign_id($society_id, 'signin_log');
				break;
			case FALSE:
				$serialized_signin_log = $by_data;
				break;
		}
		if (!empty($serialized_signin_log)) {
			$signin_log_array = unserialize($serialized_signin_log);
			foreach ($signin_log_array as $k => $v) {
				$signin_log_array[$k]['time'] = date("y/m/d H:i", $v['time']);
			}
		} else {
			$signin_log_array = '';
		}
		return $signin_log_array;
	}

	/**
	 * To set society's status & signin log
	 * @param $society_id
	 * @param $exe_user execute user name
	 * @param $exe_role execute user role(use chs constants)
	 * @param $status set society confirm flag(use null chs constants)
	 * @param $remark set society remark
	 * @param $update_type default update and oneclick update
	 */
	function _update_society_status_and_signin_log($society_id, $exe_user, $exe_role, $status, $remark = '暂无备注', $update_type = 'default') {
		switch ($update_type) {
			case 'default':
				break;
			case 'oneclick':
				$remark = '该审核由一键审核完成';
				break;
		}

		$signin_log = $this->society_model->_get_by_foreign_id($society_id, 'signin_log');
		if (empty($signin_log)) {
			$signin_log_array_length = 0;
		} else {
			$signin_log_array = unserialize($signin_log);
			$signin_log_array_length = count($signin_log_array);
		}
		 
		$signin_log_array[$signin_log_array_length]['execute_user'] = $exe_user;
		$signin_log_array[$signin_log_array_length]['execute_role'] = $exe_role;
		$signin_log_array[$signin_log_array_length]['status'] = $this->common_data->_get_society_status_by_confirm_flag($status);
		$signin_log_array[$signin_log_array_length]['time'] = time();
		$signin_log_array[$signin_log_array_length]['remark'] = ($remark) ? $remark : '暂无备注';

		$update_data['confirm_FLAG'] = $status;
		$update_data['signin_log'] = serialize($signin_log_array);
		$this->society_model->update_by_foreign_id($society_id, $update_data);
	}

	function _update_cookie($name, $value, $expire = '2592000', $path = '/') {
		if ($name == COOKIE_NEWS_READ || $name == COOKIE_SOCIETY_HOME) {
			$expire = strtotime(date('Ymd') + 1) - time(); //设置为当天过期
			$this->load->library('encrypt');
			if (!$this->input->cookie(sha1($name))) {
				$this->input->set_cookie(sha1($name), $this->encrypt->encode(serialize($value)), $expire);
				return TRUE;
			} else {
				$temp_value = unserialize($this->encrypt->decode($this->input->cookie(sha1($name))));
				if (!is_array($temp_value)) {
					if ($temp_value != $value) {
						$update_value[0] = $temp_value;
						$update_value[1] = $value;
						$this->input->set_cookie(sha1($name), $this->encrypt->encode(serialize($update_value)), $expire);
						return TRUE;
					} else {
						return FALSE;
					}
				} else {
					if (in_array($value, $temp_value)) {
						return FALSE;
					} else {
						$update_value = $temp_value;
						$update_value[count($temp_value)] = $value;
						$this->input->set_cookie(sha1($name), $this->encrypt->encode(serialize($update_value)), $expire);
						return TRUE;
					}
				}
			}
		} elseif ($name == COOKIE_USER_AUTH) {
			if (!empty($value)) {
				$salt = COOKIE_SALT;
				$identifier = $this->common->_sha1_add_salt($value['username']);
				$token = $this->common->_better_sha1_token();
				$timeout = time() + 60 * 60 * 24 * 7;
				setcookie(sha1($name), $identifier . ':' . $token, $timeout, $path);
				
				$update_data['id'] = $value['id'];
				$update_data['identifier'] = $identifier;
				$update_data['token'] = $token;
				$update_data['timeout'] = $timeout;
				$this->user_model->update($update_data);
			} else {
				setcookie(sha1($name), 'DELETED!', time(), $path);
			}
		}
	}

	function _check_cookie($name, $value) {
		if ($name == sha1(COOKIE_USER_AUTH)) {
			$salt = COOKIE_SALT;
			list($identifier, $token) = explode(':', $value);
				
			if (ctype_alnum($identifier) && ctype_alnum($token)) {
				$cookie['identifier'] = $identifier;
				$cookie['token'] = $token;
			} else {
				return FALSE;
			}
				
			$this->load->model('user_model', '', TRUE);
			$record = $this->user_model->_get_user_by_identifier($cookie['identifier']);
			
			if ($record) {
				if ($cookie['token'] != $record['token']) {
					return FALSE;
				} elseif (time() > $record['timeout']) {
					return FALSE;
				} elseif ($cookie['identifier'] != $this->common->_sha1_add_salt($record['name'])) {
					return FALSE;
				} else {
					return $record;
				}
			} else {
				return FALSE;
			}
		}
	}

	
	function _allocate_user_auth_session($data) {
		switch ($data['category_id']) {
			case SOCIETY_UCID:
				$this->load->model('society_model', '', TRUE);
				$db_data = $this->society_model->_get_by_foreign_id($data['id']);

				$this->load->model('photo_model', '', TRUE);
				$condition['society_id'] = $data['id'];
				$condition['category'] = SOCIETY_LOGO;
				$db_data2 = $this->photo_model->search_by_condition($condition, TRUE);

				/* CI SESSION */
				$session_data[SESSION_SOCIETY_ID] = $data['id'];
				$session_data[SESSION_SOCIETY_NAME] = $data['name'];
				$session_data[SESSION_SOCIETY_RE_NAME] = $db_data['s_name'];
				$session_data[SESSION_SOCIETY_RE_PERSON] = $db_data['contact'];
				if (!empty($db_data2)) {
					$session_data[SESSION_SOCIETY_LOGO_THUMB] = $db_data2['thumb_path'];
				} else {
					$session_data[SESSION_SOCIETY_LOGO_THUMB] = '';
				}
				$session_data[SESSION_SOCIETY_CONFIRM_FLAG] = $db_data['confirm_FLAG'];
				$this->session->set_userdata($session_data);

				/* PHP SESSION */
				$_SESSION['id'] = $data['id'];
				$_SESSION['ucid'] = SOCIETY_UCID;
				$_SESSION['confirm_FLAG'] = $db_data['confirm_FLAG'];
				$_SESSION['teacher_id'] = $db_data['s_teacher'];
				break;
			case ASSOCIATION_UCID:
				$this->load->model('association_model', '', TRUE);
				$condition['association_id'] = $data['id'];
				$db_data = $this->association_model->search_by_condition($condition, TRUE);

				/* CI SESSION */
				$session_data[SESSION_ASSOCIATION_ID] = $data['id'];
				$session_data[SESSION_ASSOCIATION_NAME] = $data['name'];
				$session_data[SESSION_ASSOCIATION_CID] = $db_data['a_category'];
				$session_data[SESSION_ASSOCIATION_RE_PERSON] = $db_data['a_name'];
				$session_data[SESSION_ASSOCIATION_CONFIRM_FLAG] = $db_data['confirm_FLAG'];
				$session_data[SESSION_ASSOCIATION_FUNCTION_FLAG] = $db_data['function_FLAG'];
				$this->session->set_userdata($session_data);

				/* PHP SESSION */
				$_SESSION['id'] = $data['id'];
				$_SESSION['ucid'] = ASSOCIATION_UCID;
				$_SESSION['cid'] = $db_data['a_category'];
				$_SESSION['confirm_FLAG'] = $db_data['confirm_FLAG'];
				$_SESSION['function_FLAG'] = $db_data['function_FLAG'];
				break;
			case TEACHER_UCID:
				$this->load->model('teacher_model', '', TRUE);
				$db_data = $this->teacher_model->_get_by_foreign_id($data['id']);

				$this->load->model('society_model', '', TRUE);
				$condition['s_teacher'] = $data['id'];
				$db_data2 = $this->society_model->search_by_condition($condition, TRUE);

				/* CI SESSION */
				$session_data[SESSION_TEACHER_ID] = $data['id'];
				$session_data[SESSION_TEACHER_NAME] = $data['name'];
				$session_data[SESSION_TEACHER_RE_PERSON] = $db_data['t_name'];
				$session_data[SESSION_TEACHER_DIRECT_SOCIETY] = $db_data2['s_name'];
				$this->session->set_userdata($session_data);

				/* PHP SESSION */
				$_SESSION['id'] = $data['id'];
				$_SESSION['ucid'] = TEACHER_UCID;
				$_SESSION['society_id'] = $db_data2['society_id'];
				break;
		}
	}
}